package io.github.karino2.pngnote;

import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Pair;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import io.github.karino2.pngnote.book.FastFile;
import io.github.karino2.pngnote.book.BookIO;
import io.github.karino2.pngnote.ui.Page;
import io.github.karino2.pngnote.ui.PageGridAdapter;
import io.github.karino2.pngnote.ui.PageGridData;
import io.github.karino2.pngnotemod.R;

public class PageGridActivity extends AppCompatActivity {
    private Uri dirUrl;
    private FastFile bookDir$delegate;// = bookDir_init();
    private FastFile bookDir_init() {
        Context var10001 = (Context) PageGridActivity.this;
        Uri var1 = PageGridActivity.this.dirUrl;
        Uri var10002;
        if (var1 != null) {
            var10002 = var1;
        } else {
            var10002 = null;
        }
        return FastFile.fromTreeUri(var10001, var10002);
    }

    private BookIO bookIO$delegate;// = bookIO_init();
    private BookIO bookIO_init() {
        ContentResolver var1 = PageGridActivity.this.getContentResolver();
        return new BookIO(var1);
    }

    private Book _book;
    private Bitmap bgImage$delegate;// = bgImage_init();
    private Bitmap bgImage_init() {
        return PageGridActivity.this.getBookIO().loadBgForGrid(PageGridActivity.this.getBook().getBookDir());
    }

    private List<Page> pageList$delegate;// = pageList_init();
    private List<Page> pageList_init() {
        List<Page> $this$mapIndexed$iv = null;
        $this$mapIndexed$iv = (List<Page>) PageGridActivity.this.getBook().getPages();
        PageGridActivity var2 = PageGridActivity.this;
        List<Page> destination$iv$iv = new ArrayList<Page>(
                $this$mapIndexed$iv != null ? $this$mapIndexed$iv.size() : 10);
        int index$iv$iv = 0;
        Iterator var8 = $this$mapIndexed$iv.iterator();
        while (var8.hasNext()) {
            var8.next();
            int var10 = index$iv$iv++;
            if (var10 < 0) {
                throw new IndexOutOfBoundsException(); //FIXME:
            }
            int idx = var10;
            Page var15 = new Page(String.valueOf(idx + 1), PageGridData.getBlankBitmap(), var2.getBgImage());
            destination$iv$iv.add(var15);
        }
        return destination$iv$iv;
    }

    private Pair pageSizeDP$delegate;// = pageSizeDP_init();
    private Pair pageSizeDP_init() {
        DisplayMetrics metrics = new DisplayMetrics();
        PageGridActivity.this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        return PageGridActivity.displayMetricsTo4GridSize(metrics);
    }

    private void onCreateAct() {
        bookDir$delegate = bookDir_init();
        bookIO$delegate = bookIO_init();
        bgImage$delegate = bgImage_init();
        pageList$delegate = pageList_init();
        pageSizeDP$delegate = pageSizeDP_init();
    }

    private FastFile getBookDir() {
        return this.bookDir$delegate;
    }

    private BookIO getBookIO() {
        return this.bookIO$delegate;
    }

    private Book getBook() {
        Book var1 = this._book;
        if (var1 != null) {
            Book it = var1;
            return it;
        } else {
            var1 = this.getBookIO().loadBook(this.getBookDir());
            Book it = var1;
            this._book = it;
            return it;
        }
    }

    private Bitmap getBgImage() {
        return this.bgImage$delegate;
    }

    private List getPageList() {
        return this.pageList$delegate;
    }

    private Pair getPageSizeDP() {
        return this.pageSizeDP$delegate;
    }

    private void requestLoadPages() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int idx = 0; idx < getBook().getPages().size(); ++idx) {
                    FastFile bmpfile = (FastFile) getBook().getPages().get(idx);
                    final Bitmap bitmap = getBookIO().loadPageThumbnail(bmpfile);
                    final int idx_ = idx;
                    PageGridActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            List<Page> result = new ArrayList<Page>();
                            for (int idx2 = 0; idx2 < getPageList().size(); ++idx2) {
                                Page page = (Page) getPageList().get(idx2);
                                if (idx_ == idx2) {
                                    result.add(page.copy(null, bitmap, null));
                                } else {
                                    result.add(page);
                                }
                            }
                            pageList$delegate.clear();
                            pageList$delegate.addAll(result);
                            bookGridAdapter.notifyDataSetChanged();
                        }
                    });
                }
            }
        }).start();
    }

    public void openPage(int pageIdx) {
        Intent var2 = new Intent((Context)this, BookActivity.class);
        Intent it = var2;
        it.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        it.setData(this.getBookDir().getUri());
        it.putExtra("PAGE_IDX", pageIdx);
        this.startActivity(it);
    }

    private GridView gridview;
    private PageGridAdapter bookGridAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = this.getIntent();
        if (intent != null) {
            this.dirUrl = intent.getData();
        }

        onCreateAct();

        //FIXME:
        setContentView(R.layout.activity_pagegrid);
        ActionBar topAppBar = getSupportActionBar();
        topAppBar.setTitle(getBook().getName());
        topAppBar.setIcon(R.mipmap.ic_launcher);
        topAppBar.setHomeButtonEnabled(true);
        topAppBar.setDisplayHomeAsUpEnabled(true);
        if (!Config.USE_ACTIONBAR) {
            topAppBar.hide();
        }
        findViewById(R.id.buttonBack).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        gridview = (GridView) findViewById(R.id.bookgridview);
        gridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
        gridview.setBackgroundColor(Color.WHITE);
        bookGridAdapter = new PageGridAdapter(this, getPageList());
        gridview.setAdapter(bookGridAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int pageIdx = position;
                openPage(pageIdx);
            }
        });

        this.requestLoadPages();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            //https://blog.csdn.net/aaLiweipeng/article/details/82948525
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

    public static Pair displayMetricsTo4GridSize(DisplayMetrics metrics) {
        double height = (metrics.heightPixels * 0.20 / metrics.density);
        double width = (metrics.widthPixels * 0.225 / metrics.density);
        return new Pair(width, height);
    }
}